<?php

namespace app\admin\model;
use think\Db;
use think\Model;
use my\Security;
use think\mongo\Connection;
use my\Redis;
use think\Cache;
use app\admin\model\AdminModel;

class FastCar extends Model {
    protected $cityStr = '';

    public function __construct() {
        set_time_limit(0);
        parent::__construct();
        $areaInfo = AdminModel::getRoleArea();
        if(!empty($areaInfo)){
            $this->cityStr = implode(',',$areaInfo['city']);
        }
    }

    //司机数据
    public function totalDriverInfo($dateArray=[]) {
        $where = [];
        $start_time = !empty($dateArray['start_time'])?strtotime($dateArray['start_time']):strtotime(date('Y-m-d'));
        $end_time   = !empty($dateArray['end_time'])?strtotime($dateArray['end_time']." 23:59:59"):strtotime(date('Y-m-d 23:59:59'));
        //合规状态搜索
        $whereC=[];
        $whereC['taxi_pass'] = 1;
        $whereC['taxi_certificate_pass'] = 1;
        $whereC['comm_pass'] = 1;
        $whereC['sail_pass'] = 1;
        $whereC['carriage_pass'] = 1;
        if(empty($dateArray['city_id']) && !empty($this->cityStr)){
            $dateArray['city_id'] = $this->cityStr;
        }
        if ($dateArray['city_id']){
            $whereC['work_city']= ['in',$dateArray['city_id']];
            $where['city_id']   = ['in',$dateArray['city_id']];
        }
        //查询设置 - 测试账号信息
        $whiteList = Db::name('white_list')->order('id desc')->find();
        if(!empty($dateArray['all_order']) && !empty($whiteList['driver_str'])){
            if($dateArray['all_order'] == 1){
                $where['driver_id'] = ['not in',$whiteList['driver_str']];      //普通数据
            }elseif ($dateArray['all_order'] == 2){
                $where['driver_id'] = ['in',$whiteList['driver_str']];          //测试数据
            }
        }
        $result = [];
        $where['start_time']= ['between',[$start_time,$end_time]];
        if(date("Y-m-d",$start_time) == date('Y-m-d')){
            $where['end_time']  = 0;
        }
        //查询所有司机人数
        $allDriverNumber    = Db::name('driver_base a')->join('car_info b','a.driver_id = b.driver_id','left')->where(['auth_status'=>1])->where(function ($query) use ($dateArray) {
            $whiteList      = Db::name('white_list')->order('id desc')->find();
            if(!empty($dateArray['all_order']) && (!empty($whiteList['uid_str']) || !empty($whiteList['driver_str']))){
                if($dateArray['all_order'] == 1){            //普通订单
                    $query->whereOr(['a.driver_id'=>['not in',$whiteList['driver_str']]]);
                }elseif ($dateArray['all_order'] == 2){      //测试订单
                    $query->whereOr(['a.driver_id'=>['in',$whiteList['driver_str']]]);
                }
            }
            if(!empty($dateArray['city_id'])){
                $query->where(['work_city'=>['in',$dateArray['city_id']]]);
            }
        })->count();
        //今日在线人数
        $onlineNumber       = Db::name('driver_online_time')->where($where)->group('driver_id')->count();
        //合规人数
        $compliance         = Db::name('car_info')->where($whereC)->count();
        $result = [
            'onlineNumber'  => $onlineNumber,
            'offlineNumber' => $allDriverNumber - $onlineNumber,
            'compliance'  => $compliance,
        ];
        return $result;
    }
    //快车订单数据
    public function totalOrderInfo($dateArray=[]){
        $where = [];
        //查询设置 - 测试账号信息
        $whiteList = Db::name('white_list')->order('id desc')->find();
        if(!empty($dateArray['all_order']) && (!empty($whiteList['uid_str']) || !empty($whiteList['driver_str']))){
            if($dateArray['all_order'] == 1){
                $where['uid'] = ['not in',$whiteList['uid_str']];
                $where['driver_id'] = ['not in',$whiteList['driver_str']];      //普通数据
            }elseif ($dateArray['all_order'] == 2){
                $where['uid'] = ['in',$whiteList['uid_str']];
                $where['driver_id'] = ['in',$whiteList['driver_str']];          //测试数据
            }
        }
        //时间搜索
        $start_time = !empty($dateArray['start_time'])?strtotime($dateArray['start_time']):strtotime(date('Y-m-d'));
        $end_time   = !empty($dateArray['end_time'])?strtotime($dateArray['end_time']." 23:59:59"):strtotime(date('Y-m-d 23:59:59'));
        $where['order_time']    = ['between',[$start_time,$end_time]];

        $where['is_del']        = 2;
        if (!empty($dateArray['province_id']) && empty($dateArray['city_id'])){
            //省份查询城市
            $cityArr = Db::name('region')->where(['parent_id'=>$dateArray['province_id'],'region_level'=>2])->column('region_id');
            $where['start_region_id']=['in',implode(',',$cityArr)];
        }elseif ($dateArray['city_id']){
            $where['start_region_id']=$dateArray['city_id'];
        }
        /* 2020.7.23 lili*/
        $orderInfo    = Db::name('order_common a')->field('count(*) as allOrderCount,
count(case when a.book=2 then 1 end) as allTimeCount,
count(case when a.book=1 then 1 end) as allMakeCount,
count(case when a.order_status in (0) then 1 end) as allWaitCount,
count(case when a.order_status in (5,10,12,15) then 1 end) as allCancelCount,
count(case when a.order_status=16 then 1 end) as allMakeOrderCount,
count(case when a.order_status between 17 and 30 then 1 end) as allTakeCount,
count(case when a.order_status=40 then 1 end) as allWaitSettleCount,
count(case when a.order_status>=45 then 1 end) as allFinishCount,
count(case when a.order_status>=40 AND a.abnormal_order=0 then 1 end) as allNormalCount,
count(case when a.order_status>=40 AND a.abnormal_order=1 then 1 end) as allAbnormalCount')->where($where)->find();

        /*$orderInfo['allOrderCount']     = Db::name('order_common')->where($where)->count();                                                         //订单总数
        $orderInfo['allTimeCount']      = Db::name('order_common')->where($where)->where(['book'=>2])->count();                                     //时时订单
        $orderInfo['allMakeCount']      = Db::name('order_common')->where($where)->where(['book'=>1])->count();                                     //预约订单
        $orderInfo['allWaitCount']      = Db::name('order_common')->where($where)->where(['order_status'=>['in',[0]]])->count();                    //等待接单
        $orderInfo['allCancelCount']    = Db::name('order_common')->where($where)->where(['order_status'=>['in',[5,10,12,15]]])->count();           //取消订单
        $orderInfo['allMakeOrderCount'] = Db::name('order_common')->where($where)->where(['order_status'=>16])->count();                            //预约抢单
        $orderInfo['allTakeCount']      = Db::name('order_common')->where($where)->where(['order_status'=>['between',[17,30]]])->count();           //行程中订单
        $orderInfo['allWaitSettleCount']= Db::name('order_common')->where($where)->where(['order_status'=>40])->count();                            //待结算订单
        $orderInfo['allFinishCount']    = Db::name('order_common')->where($where)->where(['order_status'=>['>=',45]])->count();                     //已完成订单
        $orderInfo['allNormalCount']    = Db::name('order_common')->where($where)->where(['order_status'=>['>=',40],'abnormal_order'=>0])->count(); //正常订单
        $orderInfo['allAbnormalCount']  = Db::name('order_common')->where($where)->where(['order_status'=>['>=',40],'abnormal_order'=>1])->count(); */
        //异常订单
        $orderInfo['allNormalRatio']    = sprintf("%.2f", $orderInfo['allNormalCount']/$orderInfo['allOrderCount'])*100;                    //正常订单比例
        $orderInfo['allAbnormalRatio']  = sprintf("%.2f", $orderInfo['allAbnormalCount']/$orderInfo['allOrderCount'])*100;                  //异常订单比例
        $orderList = Db::name('order_common')->where($where)->where(['order_status'=>['in',[5,10,12,16,17,18,30,40,45,50]]])->field('common_id,order_time,order_taker_time')->select();//查询司机接单操作 - 计算平均接单时间
        $time = 0;
        foreach ($orderList as $key=>$value){
            if(!empty($value['order_taker_time'])){
                $time += $value['order_taker_time'] - $value['order_time'];
            }
        }
        $orderNum = count($orderList);
        if(empty($time) || empty($orderNum)){
            $orderInfo['average_second']    = 0;
        }else{
            $orderInfo['average_second']    = sprintf("%.2f", $time/count($orderList));
        }
        //时时提现
        $whereTx['add_time']= ['between',[$start_time,$end_time]];
        $allTimeMoney=Db::name('driver_withdraw_flow')->where($whereTx)->where(['type'=>'=',2],['is_pay'=>'=',1])->value('SUM(money)');
        $orderInfo['allTimeMoney']=$allTimeMoney/100*-1;
        return $orderInfo;
    }

    //快车订单流水
    public function totalOrderMoney($dateArray=[]){
        $where = '';
        //时间搜索
        $start_time = !empty($dateArray['start_time'])?strtotime($dateArray['start_time']):strtotime(date('Y-m-d'));
        $end_time   = !empty($dateArray['end_time'])?strtotime($dateArray['end_time']." 23:59:59"):strtotime(date('Y-m-d 23:59:59'));
        //$where['a.pay_time']      = ['between',[$start_time,$end_time]];
        $where .=' a.pay_time between '.$start_time.' and '.$end_time;
        //查询设置 - 测试账号信息
        $whiteList = Db::name('white_list')->order('id desc')->find();

        if(!empty($dateArray['all_order']) && (!empty($whiteList['uid_str']) || !empty($whiteList['driver_str']))){
            if($dateArray['all_order'] == 1){
                //$where['a.uid'] = ['not in',$whiteList['uid_str']];
                //$where['a.driver_id'] = ['not in',$whiteList['driver_str']];      //普通数据
                $where .=' and a.uid not in ('.$whiteList['uid_str'].') and a.driver_id not in ('.$whiteList['driver_str'].')';
            }elseif ($dateArray['all_order'] == 2){
                //$where['a.uid'] = ['in',$whiteList['uid_str']];
                //$where['a.driver_id'] = ['in',$whiteList['driver_str']];          //测试数据
                $where .=' and a.uid in ('.$whiteList['uid_str'].') and a.driver_id in ('.$whiteList['driver_str'].')';
            }
        }

        if (!empty($dateArray['province_id']) && empty($dateArray['city_id'])){
            //省份查询城市
            $cityArr = Db::name('region')->where(['parent_id'=>$dateArray['province_id'],'region_level'=>2])->column('region_id');
            //$where['a.start_region_id']=['in',implode(',',$cityArr)];
            $where .=' and a.start_region_id in ('.implode(',',$cityArr).')';
        }elseif ($dateArray['city_id']){
            //$where['a.start_region_id']=$dateArray['city_id'];
            $where .=' and a.start_region_id = '.$dateArray['city_id'];
        }else{
            if(!empty($this->cityStr)){
                //$where['a.start_region_id']=['in',$this->cityStr];
                $where .=' and a.start_region_id in ('.$this->cityStr.')';
            }
        }

       /* $orderList              = Db::name('order_common')->where($where)->where(['order_status'=>['>=',40],'is_del'=>2])->field('common_id,original_price,real_fee,need_price,coupon_price,platform_price,pay_type,order_status')->select();//订单数据

        $sumRealFee = $settleRealFee = $waitRealFee = $need_price = $coupon_price = $platform_price = $balanceMoney = $alipayMoney = $wechatMoney = $driverIncomeSum = 0;
        foreach ($orderList as $key=>$value){
            $sumRealFee += $value['original_price'];                                //订单总流水
            if($value['order_status'] >= 45){
                $settleRealFee              += $value['original_price'];            //已结算
                $need_price                 += $value['need_price'];                //实付
                if($value['coupon_price'] > $value['real_fee']){
                    $coupon_price           += $value['real_fee'];                  //优惠券
                }else{
                    $coupon_price           += $value['coupon_price'];              //优惠券
                }
                $platform_price             += $value['platform_price'];            //平台费
                if($value['pay_type'] == 1){
                    $alipayMoney            += $value['need_price'];                //支付宝
                }elseif($value['pay_type'] == 2){
                    $wechatMoney            += $value['need_price'];                //微信
                }else{
                    $balanceMoney           += $value['need_price'];               //余额
                }
                //查询司机接单操作 - 计算司机收入
                $driverIncome               = Db::name('driver_wallet_record')->where(['record_type' => ['in',[1,5]], 'common_id' => $value['common_id']])->value('money');
                $driverIncomeSum            += $driverIncome;
            }
        }*/

        $orderList= Db::name('order_common a,xm_driver_wallet_record b')
            ->where($where.' and a.order_status>=40 and a.is_del=2 and a.common_id=b.common_id')
            ->field('SUM(a.original_price) AS sumRealFee,
	SUM( CASE WHEN a.order_status >= 45 THEN a.original_price END ) AS settleRealFee,
	SUM( CASE WHEN a.order_status >= 45 THEN a.need_price END ) AS need_price,
	SUM( CASE WHEN a.order_status >= 45 AND a.coupon_price > a.real_fee THEN a.real_fee ELSE a.coupon_price END ) AS coupon_price,
	SUM( CASE WHEN a.order_status >= 45 THEN a.platform_price END ) AS platform_price,
	SUM( CASE WHEN a.order_status >= 45 AND a.pay_type = 1 THEN a.need_price END ) AS alipayMoney,
	SUM( CASE WHEN a.order_status >= 45 AND a.pay_type = 2 THEN a.need_price END ) AS wechatMoney,
	SUM( CASE WHEN a.order_status >= 45 AND a.pay_type != 1 AND a.pay_type != 2 THEN a.need_price END ) AS balanceMoney,
	SUM( CASE WHEN a.order_status >= 45 AND b.record_type IN (1, 5) THEN b.money END ) AS driverIncomeSum')
            ->find();//订单数据

        $orderInfo = [
            'sumRealFee'        => !empty($orderList['sumRealFee'])?sprintf("%.2f", $orderList['sumRealFee']/100):0,
            'settleRealFee'     => !empty($orderList['sumRealFee'])?sprintf("%.2f", $orderList['settleRealFee']/100):0,
            'waitRealFee'       => !empty($orderList['sumRealFee'])?sprintf("%.2f", ($orderList['sumRealFee']-$orderList['settleRealFee'])/100):0,
            'need_price'        => !empty($orderList['sumRealFee'])?sprintf("%.2f", $orderList['need_price']/100):0,
            'coupon_price'      => !empty($orderList['sumRealFee'])?sprintf("%.2f", $orderList['coupon_price']/100):0,
            'platform_price'    => !empty($orderList['sumRealFee'])?sprintf("%.2f", $orderList['platform_price']/100):0,
            'alipayMoney'       => !empty($orderList['sumRealFee'])?sprintf("%.2f", $orderList['alipayMoney']/100):0,
            'wechatMoney'       => !empty($orderList['sumRealFee'])?sprintf("%.2f", $orderList['wechatMoney']/100):0,
            'balanceMoney'      => !empty($orderList['sumRealFee'])?sprintf("%.2f", $orderList['balanceMoney']/100):0,
            'average_money'     => !empty($orderList['driverIncomeSum'])?sprintf("%.2f", $orderList['driverIncomeSum'] / 100):0
        ];
        return $orderInfo;
    }
    //24小时订单数据
    public function totalOrderNumber($dateTimeArr=[],$dateArray=[]){
        $where = '';
        //查询设置 - 测试账号信息
        $whiteList = Db::name('white_list')->order('id desc')->find();
        if(!empty($dateArray['all_order']) && (!empty($whiteList['uid_str']) || !empty($whiteList['driver_str']))){
            if($dateArray['all_order'] == 1){
                //$where['uid'] = ['not in',$whiteList['uid_str']];
                //$where['driver_id'] = ['not in',$whiteList['driver_str']];      //普通数据

                $where .=' and uid not in('.$whiteList['uid_str'].')';
                $where .=' and driver_id not in('.$whiteList['driver_str'].')';
            }elseif ($dateArray['all_order'] == 2){
                //$where['uid'] = ['in',$whiteList['uid_str']];
                //$where['driver_id'] = ['in',$whiteList['driver_str']];          //测试数据

                $where .=' and uid in('.$whiteList['uid_str'].')';
                $where .=' and driver_id in('.$whiteList['driver_str'].')';
            }
        }
        if (!empty($dateArray['province_id']) && empty($dateArray['city_id'])){
            //省份查询城市
            $cityArr = Db::name('region')->where(['parent_id'=>$dateArray['province_id'],'region_level'=>2])->column('region_id');
            //$where['start_region_id']=['in',implode(',',$cityArr)];
            $where .=' and start_region_id in('.implode(',',$cityArr).')';
        }elseif ($dateArray['city_id']){
            //$where['start_region_id']=$dateArray['city_id'];
            $where .=' and start_region_id ='.$dateArray['city_id'];
        }else{
            if(!empty($this->cityStr)){
                //$where['start_region_id']=['in',$this->cityStr];
                $where .=' and start_region_id in('.$this->cityStr.')';
            }
        }
        $arr=array();
        //24小时拆分
        $times=time();
        $start_time = date("Y-m-d",$times);
        $end_time   = date("Y-m-d",strtotime('+1 day',$times));

        $sql="SELECT timetable. HOUR HOUR, ifnull(sumtable.count, 0) Count FROM ( SELECT a.region_id - 1 AS HOUR FROM xm_region a ORDER BY a.region_id ASC LIMIT 24 ) timetable LEFT JOIN ( SELECT HOUR (FROM_UNIXTIME(b.order_time, '%Y-%m-%d %H')) HOUR, count(b.common_id) count FROM xm_order_common b WHERE b.is_del = 2 and FROM_UNIXTIME(b.order_time, '%Y-%m-%d') between '".$start_time."' and '".$end_time."'".$where." GROUP BY date_format(b.order_time, '%Y%m%d-%H'), HOUR ) sumtable ON timetable. HOUR = sumtable. HOUR ORDER BY HOUR";
        $orderInfo = Db::query($sql);

        /* 优化,使用上面的原生sql lili 2020.7.25
         * $orderInfo       = Db::name('order_common')
            ->field("HOUR (FROM_UNIXTIME(order_time, '%Y-%m-%d %H:%i:%s')) AS hours,count(*) AS Count")
            ->where($where)
            ->group("HOUR (FROM_UNIXTIME(order_time, '%Y-%m-%d %H:%i:%s'))")
            ->order('order_time')
            ->select();*/

        /*for($i = 0 ; $i <= 23 ; $i++){

        //上一任写的 ssss
//            foreach($dateTimeArr as $key=>$value){
//                if(strlen($i) == 1){
//                    $i = '0'.$i;
//                }
//                $start_time = $dateTimeArr." ". $i .":00:00";
//                $end_time   = $dateTimeArr." ". $i .":59:59";
//                $where['order_time']    = ['between',[strtotime($start_time),strtotime($end_time)]];
//                $where['is_del']        = 2;
//                $orderInfo[$i]       = Db::name('order_common')->where($where)->count();
//            }
        //eeee

            if(count($orderInfo)>0){
                foreach($orderInfo as $key=>$value){
                    if($value['hours']==$i){
                        $arr[$i]=$value['Count'];
                    }else{
                        $arr[$i]=0;
                    }
                }
            }else{
                $arr[$i]=0;
            }
        }*/
//// ssss
//        foreach ($orderInfo as $key=>$value){
//            $sumOrderNum = 0;
//            foreach ($value as $val){
//                $sumOrderNum += $val;
//            }
//            $arr[] = $sumOrderNum;
//        }
//// eeee
        foreach($orderInfo as $key=>$value){
            $arr[$value['HOUR']]=$value['Count'];
        }
        $sumOrderNumStr = implode(',',$arr);
        return $sumOrderNumStr;
    }

    //快车司机排行
    public function getDriverList($page, $limit,$dateArray=[]){
        //查询设置 - 测试账号信息
        $whiteList = Db::name('white_list')->order('id desc')->find();
        if(!empty($dateArray['all_order']) && !empty($whiteList['driver_str'])){
            if($dateArray['all_order'] == 1){
                $where['driver_id'] = ['not in',$whiteList['driver_str']];      //普通数据
            }elseif ($dateArray['all_order'] == 2){
                $where['driver_id'] = ['in',$whiteList['driver_str']];          //测试数据
            }
        }
        $start_time = !empty($dateArray['start_time'])?strtotime($dateArray['start_time']):strtotime(date('Y-m-d'));
        $end_time   = !empty($dateArray['end_time'])?strtotime($dateArray['end_time']." 23:59:59"):strtotime(date('Y-m-d 23:59:59'));
        $orderWhere['order_time']  = ['between',[$start_time,$end_time]];
        $onlineWhere['start_time'] = ['between',[$start_time,$end_time]];
        if(!empty($dateArray['driver_phone'])){
            $where['driver_phone'] = Security::encrypt($dateArray['driver_phone']);
        }
        $where['auth_status'] = 1;
        $count          = Db::name('driver_base')->where($where)->field('driver_id,driver_phone,driver_name')->count();
        $driverList     = Db::name('driver_base')->where($where)->field('driver_id,driver_phone,driver_name')->select();
        //循环司机信息 - 统计司机接单数量 - 在线时间 - 评分
        $orderList = [];
        $driver_str = 0;
        foreach ($driverList as $key=>$vml){
            $driverList[$key]['driver_phone']           = Security::decrypt($vml['driver_phone']);
            //查询司机信息
            $driver_str .= $vml['driver_id'].',';
        }
        //订单信息处理
        $orderArr = [];
        $orderList = Db::name('order_common')->where($orderWhere)->where(['order_status'=>['in',[5,10,12,16,17,18,30,40,45,50]],'is_del'=>2,'driver_id'=>['in',rtrim($driver_str,',')]])->field('driver_id,abnormal_order,order_time,order_taker_time,order_status,original_price')->select();
        foreach ($orderList as $key=>$value){
            //接单数量
            $orderArr[$value['driver_id']]['catchOrderNum']         += 1;
            //接单时间
            if(!empty($value['order_taker_time'])){
                $orderArr[$value['driver_id']]['catchOrderTime']     += $value['order_taker_time'] >= $value['order_time']?$value['order_taker_time'] - $value['order_time']:0;
            }else{
                $orderArr[$value['driver_id']]['catchOrderTime']     += 0;
            }
            //完成订单数量
            if($value['order_status'] >= 40){
                $orderArr[$value['driver_id']]['finishOrderNum']     += 1;                                              //已完成订单数量
                if($value['abnormal_order'] == 1){
                   $orderArr[$value['driver_id']]['allAbnormalCount']+= 1;                                              //异常订单数量
                }else{
                   $orderArr[$value['driver_id']]['allNormalCount']  += 1;                                              //正常订单数量
                }
            }
            //待结算订单
            if($value['order_status'] == 40){
                $orderArr[$value['driver_id']]['waitOrderNum']       += 1;                                              //未结算订单
            }
            //已完成订单
            if($value['order_status'] >= 45){
                $orderArr[$value['driver_id']]['finishOrderMoney']   += $value['original_price'];                       //已完成的订单金额
            }
        }
        //查询累计司机在线时长
        $onlineTimeList = Db::name('driver_online_time')->where($onlineWhere)->where(['driver_id'=>['in',rtrim($driver_str,',')]])->order('id desc')->select();
        //如果是一条记录
        $timeArr        = [];
        $sum_time       = 0;
        foreach ($onlineTimeList as $kly=>$vmll){
            if($kly == 0 && empty($onlineTimeList[$kly]['end_time'])){
                $sum_time = time() - $vmll['start_time'];
            }else{
                if(!empty($vmll['end_time'])){
                    $sum_time = $vmll['end_time'] - $vmll['start_time'];
                }else{
                    $sum_time = $onlineTimeList[$kly-1]['start_time'] - $vmll['start_time'];
                }
            }
            $timeArr[$vmll['driver_id']]['timeCount'] += $sum_time;
        }
        //处理司机评分
        $commentList = Db::name('comment')->where(['driver_id'=>['in',rtrim($driver_str,',')]])->field('driver_id,service_rank')->select();
        $result = [];
        foreach ($commentList as $key=>$value){
            $result[$value['driver_id']]['num']         += 1;
            $result[$value['driver_id']]['sorce']       += $value['service_rank'];
        }
        //处理司机订单 + 在线时长 + 评分
        foreach ($driverList as $key=>$value){
            $driverList[$key]['catchOrderNum']          = !empty($orderArr[$value['driver_id']]['catchOrderNum'])?$orderArr[$value['driver_id']]['catchOrderNum']:0;
            $driverList[$key]['catchOrderTime']         = !empty($orderArr[$value['driver_id']]['catchOrderTime'])?sprintf("%.2f", $orderArr[$value['driver_id']]['catchOrderTime']/$orderArr[$value['driver_id']]['catchOrderNum']):9999999;
            $driverList[$key]['finishOrderNum']         = !empty($orderArr[$value['driver_id']]['finishOrderNum'])?$orderArr[$value['driver_id']]['finishOrderNum']:0;
            $driverList[$key]['waitOrderNum']           = !empty($orderArr[$value['driver_id']]['waitOrderNum'])?$orderArr[$value['driver_id']]['waitOrderNum']:0;
            $driverList[$key]['finishOrderMoney']       = !empty($orderArr[$value['driver_id']]['finishOrderMoney'])?sprintf("%.2f", $orderArr[$value['driver_id']]['finishOrderMoney']/100):0;
            $driverList[$key]['allNormalCount']         = !empty($orderArr[$value['driver_id']]['allNormalCount'])?$orderArr[$value['driver_id']]['allNormalCount']:0;
            $driverList[$key]['allAbnormalCount']       = !empty($orderArr[$value['driver_id']]['allAbnormalCount'])?$orderArr[$value['driver_id']]['allAbnormalCount']:0;
            //司机在线时长
            $driverList[$key]['sumTime']                = $timeArr[$value['driver_id']]['timeCount'];
            $driverList[$key]['sumOnlineTime']          = get_second_h_m($timeArr[$value['driver_id']]['timeCount']);
            //司机评分
            if(empty($result[$value['driver_id']]['num'])){
                $driverList[$key]['score']              = 0;
            }else{
                $driverList[$key]['score']              = !empty($result[$value['driver_id']]['sorce'])?sprintf("%.1f", $result[$value['driver_id']]['sorce']/$result[$value['driver_id']]['num']):0;
            }
        }
        if($dateArray['rank'] == 1 || empty($dateArray['rank'])){
            $sort = array_column($driverList,'catchOrderNum');
        }elseif($dateArray['rank'] == 2){
            $sort = array_column($driverList,'catchOrderTime');
        }elseif($dateArray['rank'] == 3){
            $sort = array_column($driverList,'finishOrderNum');
        }elseif($dateArray['rank'] == 4){
            $sort = array_column($driverList,'waitOrderNum');
        }elseif($dateArray['rank'] == 5){
            $sort = array_column($driverList,'finishOrderMoney');
        }elseif($dateArray['rank'] == 6){
            $sort = array_column($driverList,'allNormalCount');
        }elseif($dateArray['rank'] == 7){
            $sort = array_column($driverList,'allAbnormalCount');
        }elseif($dateArray['rank'] == 8){
            $sort = array_column($driverList,'sumTime');
        }elseif($dateArray['rank'] == 9){
            $sort = array_column($driverList,'score');
        }
        //接单时间排序 从小到大
        if($dateArray['rank'] == 2){
            array_multisort($sort,SORT_ASC,$driverList);
        }else{
            array_multisort($sort,SORT_DESC,$driverList);
        }
        $i = 1;
        foreach ($driverList as $key=>$value){
            $driverList[$key]['top'] = $i;
            $i++;
        }
        $driverList = self::arr_page($driverList,$page,$limit);
        return array(
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $driverList
        );
    }
    //二维数据排序
    public function arr_page($arr,$p,$count){
        if (empty($p)){
            $p = 1;
        }
        if (empty($count)){
            $count = 10;
        }
        $start = ($p-1)*$count;
        for ($i=$start;$i<$start+$count;$i++){
            if (!empty($arr[$i])){
                $new_arr[$i] = $arr[$i];
            }
        }
        return $new_arr;
    }
    //司机位置信息
    public function driverList($page,$limit,$data){
        $driverList     = self::driverListMongo($data);
        $orderInfo        = self::OrderListMongo();
        //通过 坐标查询地址
        $addressArr     = [];
        foreach ($driverList as $key=>$value){
            //获取身边订单
            $jw2=[$value['lng'],$value['lat']];
            $common_ids=self::compareJW($jw2,$orderInfo);
            $driverList[$key]['orderInfo']=Db::name('order_common')->where('common_id','in',$common_ids)->select();
            $driverList[$key]['orderCount']=count($driverList[$key]['orderInfo']);
            $addressKey = 'driverAdressKey:'.$value['driverId'];
            $addressName= Cache::get($addressKey);
            if(empty($addressName)){
                $url = "https://restapi.amap.com/v3/geocode/regeo?key=54fcf57140fcf3061dfa704083f4d8e0&location=".$value['lng'].','.$value['lat'];
                $addressArr = https_request($url);
                $addressArr = json_decode($addressArr,true);
                if(!empty($addressArr) && $addressArr['status'] == 1){
                    $driverList[$key]['addressName'] = $addressArr['regeocode']['formatted_address'];
                }else{
                    $driverList[$key]['addressName'] = $value['lng'].','.$value['lat'];
                }
                Cache::set($addressKey,$driverList[$key]['addressName']);
            }else{
                if($value['localType'] == 1){
                    $driverList[$key]['addressName']    = Cache::get($addressKey);
                }else{
                    $url = "https://restapi.amap.com/v3/geocode/regeo?key=54fcf57140fcf3061dfa704083f4d8e0&location=".$value['lng'].','.$value['lat'];
                    $addressArr = https_request($url);
                    $addressArr = json_decode($addressArr,true);

                    if(!empty($addressArr) && $addressArr['status'] == 1){
                        $driverList[$key]['addressName'] = $addressArr['regeocode']['formatted_address'];
                    }else{
                        $driverList[$key]['addressName'] = $value['lng'].','.$value['lat'];
                    }
                    Cache::set($addressKey,$driverList[$key]['addressName']);
                }
            }
        }
        $sort = array_column($driverList,'sumTime');
        array_multisort($sort,SORT_DESC,$driverList);
        $list = self::arr_page($driverList,$page,$limit);
        return array(
            'code'  => 0,
            'msg'   => '',
            'count' => count($driverList),
            'data'  => $list
        );
    }
    //处理司机信息
    public function driverListMongo($data){
        $province_id    = !empty($data['province_id'])?$data['province_id']:13;     //省份搜索
        $city_id        = !empty($data['city_id'])?$data['city_id']:133;            //城市搜索
        $driver_name    = !empty($data['driver_name'])?$data['driver_name']:'';     //司机姓名
        $driver_phone   = !empty($data['driver_phone'])?$data['driver_phone']:'';   //司机手机号
        $where          = [];
        $where['b.driver_type'] = $data['driver_type'];
        if(!empty($driver_name)){
            $driverInfo = Db::name('driver_base')->where(['driver_name'=>['like','%'.$driver_name.'%']])->field('driver_id')->select();
            $driverArrId = [];
            foreach ($driverInfo as $key=>$value){
                $driverArrId[] = $value['driver_id'];
            }
            $where['a.driver_id'] = ['in',implode(',',$driverArrId)];
        }
        if(!empty($driver_phone)){
            $where['a.driver_id'] = Db::name('driver_base')->where(['driver_phone'=>Security::encrypt($driver_phone)])->value('driver_id');
        }
        $mongoCollection    = new Connection();
        $driverLocation     = $mongoCollection->table("live_driver_location")->field('driverId,location,createTime,direction')->select();
        $driverIdArr        = [];
        $driverLocationArr  = [];
        $dqtime=strtotime(date('Y-m-d'));//当前时间戳
        foreach ($driverLocation as $key =>$value){                                                                     //第一层过滤司机
            if(!empty($value['createTime'])){
                $createTime = substr($value['createTime'], 0, -3);
                if(strstr($value['createTime'],':')){
                    $createTime = strtotime($value['createTime']);
                }
                if($createTime > $dqtime){
                    $driverIdArr[] = $value['driverId'];
                    $driverLocationArr[$value['driverId']] = $value;
                }
            }
        }
        //查询这些司机的认证城市 - 并且是否认证通过 - 符合的司机信息
        $driverList = Db::name('car_info')->alias('a')->field('a.driver_id as driverId,b.driver_name as name,b.driver_phone')->join('driver_base b','a.driver_id = b.driver_id','left')->where(['a.driver_id'=>['in',implode(',',$driverIdArr)],'a.work_province'=>$province_id,'a.work_city'=>$city_id,'b.auth_status'=>1])->where($where)->select();
        foreach ($driverList as $key=>$value){
            $driverList[$key]['driver_phone'] = Security::decrypt($value['driver_phone']);
        }
        //符合的司机
        $redis = new Redis();
        foreach ($driverList as $key=>$value){
            $driverLocal = [];
            if(!empty($driverLocationArr[$value['driverId']])){        //不为空
                $hashKey                = 'driver_id:'.$value['driverId'];
                //判断上一次司机坐标哈希数据是否存在
                if($redis->Exists($hashKey)){
                    $driverLocal        = $redis->hGetAll($hashKey);
                    if($driverLocal['lng'] == $driverLocationArr[$value['driverId']]['location']['coordinates'][0] && $driverLocal['lat'] == $driverLocationArr[$value['driverId']]['location']['coordinates'][1]){
                        $driverList[$key]['localType']      = 1;
                        $driverList[$key]['time']           = get_second_h_m(time() - $driverLocal['time']);
                        $driverList[$key]['sumTime']        = time() - $driverLocal['time'];
                    }else{
                        $driverList[$key]['localType']      = 0;
                        $driverList[$key]['time']           = '-';
                        $driverList[$key]['sumTime']        = 0;
                        $driverLocal = [
                            'time'          => time(),
                            'lng'           => $driverLocationArr[$value['driverId']]['location']['coordinates'][0],
                            'lat'           => $driverLocationArr[$value['driverId']]['location']['coordinates'][1]
                        ];
                        $redis->hMSet($hashKey,$driverLocal);
                    }
                }else{
                    $driverList[$key]['localType']          = 0;
                    $driverList[$key]['time']               = '-';
                    $driverList[$key]['sumTime']            = 0;
                    $driverLocal = [
                        'time'          => time(),
                        'lng'           => $driverLocationArr[$value['driverId']]['location']['coordinates'][0],
                        'lat'           => $driverLocationArr[$value['driverId']]['location']['coordinates'][1]
                    ];
                    $redis->hMSet($hashKey,$driverLocal);
                }
                $driverList[$key]['lng']        = $driverLocationArr[$value['driverId']]['location']['coordinates'][0];
                $driverList[$key]['lat']        = $driverLocationArr[$value['driverId']]['location']['coordinates'][1];
                $driverList[$key]['old_lng']    = !empty($driverLocal['lng'])?$driverLocal['lng']:'';
                $driverList[$key]['old_lat']    = !empty($driverLocal['lat'])?$driverLocal['lat']:'';
                $driverList[$key]['center']     = $driverLocationArr[$value['driverId']]['location']['coordinates'][0].','.$driverLocationArr[$value['driverId']]['location']['coordinates'][1];
                $driverList[$key]['direction']  = $driverLocationArr[$value['driverId']]['direction'];
            }
        }
        return $driverList;
    }
    /**
     * 处理乘客信息
     */
    public function OrderListMongo(){
        $mongoCollection    = new Connection();
        $passengerLocation     = $mongoCollection->table("live_user_location")->field('uId,orderId,location,createTime')->select();
        $orderId=[];
        foreach ($passengerLocation as $key =>$value){                                                                     //第一层过滤司机
            if(!empty($value['createTime'])){
                $createTime = substr($value['createTime'], 0, -3);
                if($createTime > strtotime('Y-m-d')){
                    $orderId[$key] = $value['orderId'];
                }
            }
        }
           $orderLists=Db::name('order_common')->where('common_id','in',$orderId)->select();
        $order=[];
        foreach ($orderLists as $k=>$v){
            $order[$k]['common_id']=$v['common_id'];
            $order[$k]['book']=$v['book'];
            $order[$k]['book_time']=$v['book_time'];
            $order[$k]['order_time']=$v['order_time'];
            $order[$k]['order_sn']=$v['order_sn'];
            $order[$k]['uid']=$v['uid'];
            $order[$k]['start_local']=Security::decrypt($v['start_local']);
            $order[$k]['start_name']=Security::decrypt($v['start_name']);
            $order[$k]['arrive_local']=Security::decrypt($v['arrive_local']);
            $order[$k]['arrive_local']=Security::decrypt($v['arrive_local']);
            $order[$k]['arrive_name']=Security::decrypt($v['arrive_name']);
            $order[$k]['jw']=explode(',',$order[$k]['start_local']);

        }
        return $order;
    }
    /**比对经纬度3公里内(粗略)
     * 从data2里寻找data1，3公里内的单子
     * @param $data1
     * @param $data2
     */
    public function compareJW($data1,$data2){
        $common_id=[];
        $lng=$data1[0];
        $lat=$data1[1];
        foreach ($data2 as $k=>$v){
            //经纬度区间
            if (($v['jw'][0]-0.001<$lng&&$v['jw'][0]+0.001>$lng)&&($v['jw'][1]-0.001<$lat&&$v['jw'][1]+0.001>$lat)){
                $common_id[$k]=$v['common_id'];
            }
        }

        return $common_id;
    }
}
